package com.fuyun.rpc.client.fault.tolerant;

import com.fuyun.rpc.common.domain.RpcResponse;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 快速失败容错策略（增加熔断器支持）
 *
 * @author: zrq1351
 * @date: 2025/2/17
 */
public class FailFastTolerantStrategy implements TolerantStrategy {

	// 为每个服务维护一个熔断器
	private static final Map<String, CircuitBreaker> CIRCUIT_BREAKERS = new ConcurrentHashMap<>();

	// 熔断器配置参数
	private static final int FAILURE_THRESHOLD = 5;      // 失败阈值
	private static final long TIMEOUT = 60000;          // 超时时间(毫秒)
	private static final int SUCCESS_THRESHOLD = 2;      // 半开状态下成功阈值

	@Override
	public RpcResponse doTolerant(Map<String, Object> context, Exception e) {
		String serviceName = (String)context.get("serviceName");
		if (serviceName != null) {
			CircuitBreaker circuitBreaker = CIRCUIT_BREAKERS.computeIfAbsent(serviceName, key -> new CircuitBreaker(
				FAILURE_THRESHOLD, TIMEOUT, SUCCESS_THRESHOLD));
			circuitBreaker.onFailure();
		}

		throw new RuntimeException("服务报错", e);
	}

	/**
	 * 获取服务对应的熔断器
	 * @param serviceName 服务名称
	 * @return 熔断器
	 */
	public static CircuitBreaker getCircuitBreaker(String serviceName) {
		return CIRCUIT_BREAKERS.get(serviceName);
	}
}